package com.atguigu.gulimall.cart.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.atguigu.common.constant.CartConstant;
import com.atguigu.common.utils.R;
import com.atguigu.gulimall.cart.feign.ProductFeignService;
import com.atguigu.gulimall.cart.interceptor.CartInterceptor;
import com.atguigu.gulimall.cart.service.CartService;
import com.atguigu.gulimall.cart.to.UserInfoTo;
import com.atguigu.gulimall.cart.vo.Cart;
import com.atguigu.gulimall.cart.vo.CartItem;
import com.atguigu.gulimall.cart.vo.SkuInfoVo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundHashOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.stream.Collectors;

@Service
@Slf4j
public class CartServiceImpl implements CartService {


    @Autowired
    StringRedisTemplate redisTemplate;

    @Autowired
    ProductFeignService productFeignService;

    @Autowired
    ThreadPoolExecutor executor;

    @Override
    public CartItem addToCart(Long skuId, int num) {

        BoundHashOperations<String, Object, Object> cartOps = getCartOps();
        String res = (String) cartOps.get(skuId.toString());

        if (StringUtils.isEmpty(res)) {

            CartItem cartItem = new CartItem();
            CompletableFuture<Void> skuInfoTask = CompletableFuture.runAsync(() -> {
                //1.得到商品詳情
                R r = productFeignService.skuInfo(skuId);

                if (r.getCode() == 0) {
                    SkuInfoVo sku = r.getData("skuInfo", new TypeReference<SkuInfoVo>() {
                    });
                    cartItem.setCount(num);
                    cartItem.setCheck(true);
                    cartItem.setImage(sku.getSkuDefaultImg());
                    cartItem.setPrice(sku.getPrice());
                    cartItem.setTitle(sku.getSkuTitle());
                    cartItem.setSkuId(skuId);
                }
            }, executor);

            //cartItem需要sku組合信息

            CompletableFuture<Void> atttrGroupTask = CompletableFuture.runAsync(() -> {
                List<String> attrs = productFeignService.getSkuSaleAttrValues(skuId);
                if (attrs != null) {
                    cartItem.setSkuAttr(attrs);
                }
            }, executor);

            CompletableFuture<Void> allTask = CompletableFuture.allOf(skuInfoTask, atttrGroupTask);
            try {
                allTask.get();
            } catch (InterruptedException | ExecutionException e) {
                e.printStackTrace();
            }


            //添加到redis存儲
            cartOps.put(skuId.toString(), JSON.toJSONString(cartItem));
            return cartItem;
        } else {
            CartItem cartItem = JSON.parseObject(res, new TypeReference<CartItem>() {});
            cartItem.setCount(cartItem.getCount() + num);
            cartOps.put(skuId.toString(), JSON.toJSONString(cartItem));
            return cartItem;
        }
    }

    @Override
    public CartItem getCartItem(Long skuId) {
        BoundHashOperations<String, Object, Object> cartOps = getCartOps();
        String cartStr = (String) cartOps.get(skuId.toString());
        return JSON.parseObject(cartStr, new TypeReference<CartItem>() {
        });
    }

    @Override
    public Cart getCart() {
        Cart cart = new Cart();
        ThreadLocal<UserInfoTo> threadLocal = CartInterceptor.threadLocal;
        UserInfoTo userInfoTo = threadLocal.get();
        String cartKey = "";
        if (userInfoTo.getUserId() != null) {
            //用戶已經登錄，將臨時購物車的數據合并到用戶購物車中，清空臨時購物車，刪除用戶數據

            cartKey = CartConstant.CART_PREFIX + userInfoTo.getUserKey();
            List<CartItem> tempCartItems = getCartItems(cartKey);

            //此時是登錄轉臺，調用addToCart必然是合并而不是添加
            if (tempCartItems != null) {
                for (CartItem tempCartItem : tempCartItems) {
                    addToCart(tempCartItem.getSkuId(), tempCartItem.getCount());
                }
            }
            //清空零時購物車
            clearCart(cartKey);

            //再查一次，必然是全量數據
            cartKey =CartConstant.CART_PREFIX + userInfoTo.getUserId();
            List<CartItem> cartItems = getCartItems(cartKey);
            cart.setItems(cartItems);
            return cart;
        } else {
            cartKey = CartConstant.CART_PREFIX + userInfoTo.getUserKey();
            cart.setItems(getCartItems(cartKey));
        }
        return cart;
    }

    @Override
    public void clearCart(String cartKey) {
        redisTemplate.delete(cartKey);
    }

    @Override
    public void checkItem(Long skuId, Integer check) {
        CartItem cartItem = getCartItem(skuId);
        cartItem.setCheck(check==1);
        getCartOps().put(skuId.toString(), JSON.toJSONString(cartItem));
    }

    @Override
    public void changeItemCount(Long skuId, Integer num) {
        CartItem cartItem = getCartItem(skuId);
        cartItem.setCount(num);
        getCartOps().put(skuId.toString(), JSON.toJSONString(cartItem));
    }

    @Override
    public void deleteItem(Long skuId) {
        getCartOps().delete(skuId.toString());
    }

    @Override
    public List<CartItem> getUserCartItems() {
        UserInfoTo userInfoTo = CartInterceptor.threadLocal.get();
        if (userInfoTo.getUserId() == null) {
            return null;
        }
        //获取选中的最新的购物项信息（价格最新）
       String cartKey =CartConstant.CART_PREFIX + userInfoTo.getUserId();
        List<CartItem> cartItems = getCartItems(cartKey);
        if (cartItems == null) {
            return null;
        }
        return cartItems.stream().filter(CartItem::getCheck).
                peek(item -> item.setPrice(new BigDecimal((String)productFeignService.getPrice(item.getSkuId()).get("data")))).
                collect(Collectors.toList());
    }

    private List<CartItem> getCartItems(String cartKey) {
        BoundHashOperations<String, Object, Object> cartOps = redisTemplate.boundHashOps(cartKey);
        List<Object> values = cartOps.values();
        if (values != null && values.size() > 0) {
            return values.stream().map((o) -> JSON.parseObject((String)o, CartItem.class)).collect(Collectors.toList());
        }
        return null;
    }

    private BoundHashOperations<String, Object, Object> getCartOps() {
        UserInfoTo userInfoTo = CartInterceptor.threadLocal.get();
        String cartKey = "";
        if (userInfoTo.getUserId() != null) {
            //用戶已經登錄，存儲到用戶購物車
            cartKey =CartConstant.CART_PREFIX + userInfoTo.getUserId();
        } else {
            cartKey = CartConstant.CART_PREFIX + userInfoTo.getUserKey();
        }
        return redisTemplate.boundHashOps(cartKey);
    }
}
